﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Baosight.ZNH.ZMCommon;
using Baosight.Platform.Core;
using Telerik.Windows.Controls;
using Baosight.ZNH.ZMCommon.ChildWindows;
using Baosight.Platform.Core.UI;
using Baosight.ZNH.ZMCE.UI.PopWindows;
using Microsoft.Practices.Unity;
using Telerik.Windows.Controls.GridView;
using Baosight.ZNH.ZMCE.UI.Blocks;
using Baosight.Platform.Core.UI.Controls;
using Baosight.Platform.Core.ServiceModel;

namespace Baosight.ZNH.ZMCE.UI
{
    /// <summary>
    /// 设备卡片
    /// </summary>
    /// Copyright:Baosight Software LTD.co Copyright (c) 2011
    /// Company:上海宝信软件股份有限公司
    /// Author: 张志芳
    /// Version: 1.0
    /// History:
    ///       2011-07-08  张志芳   [创建]
    ///
    public partial class ZMCEC1 : EFViewCmes
    {
        private Dictionary<object, string> TabToPageName; //存放页签与页面号的对应关系
        private string ButtonName = "";
        public ZMCEC1()
        {
            InitializeComponent();
            TabToPageName = new Dictionary<object, string>();
            TabToPageName.Add(tab1, "ZMCEC2");
            TabToPageName.Add(tab2, "ZMCEC3");
            TabToPageName.Add(tab3, "ZMCEC4");
            TabToPageName.Add(tab4, "ZMCEC5");
            TabToPageName.Add(tab5, "ZMCEB2");
            TabToPageName.Add(tab6, "ZMCEB3");
            TabToPageName.Add(tab7, "ZMCEB4");
            TabToPageName.Add(tab8, "ZMCEB5");
            base.BeforeAction += OnBeforeAction;
        }

        /// <summary>
        /// 列表中修改、删除前设置属性、参数
        /// 传递到后台代码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBeforeAction(object sender, EventArgs e)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.EFGridCheckedRows = this.grid.GetCheckedEIRows();
            base.ViewProperty = _view;
        }

        public override void Initialize(EIInfo initData)
        {
            EquipmentCardBlock block = new EquipmentCardBlock();
            initData.AddBlock(block.getIntactType("cmes.ce.intactType"));
            initData.AddBlock(block.getStatus("cmes.ce.status"));
            base.Initialize(initData);
        }


        /// <summary>
        /// 选中主表一条记录，显示该条记录的从表数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grid_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangeEventArgs e)
        {
            if (this.grid.SelectedItem != null)
            {
                LoadTab(this.grid.SelectedItem, this.tabPage.SelectedItem);
            }
            else
            {
                (this.tabPage.SelectedItem as EFTabItem).Content = null;
            }
        }

        /// <summary>
        /// 页签改变加载不同的页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EFTab_SelectionChanged(object sender, RoutedEventArgs e)
        {
            EFTab tab = sender as EFTab;
            if (this.grid.SelectedItem != null)
            {
                LoadTab(this.grid.SelectedItem, tab.SelectedItem);
            }
        }

        /// <summary>
        /// 加载不同的页签
        /// </summary>
        /// <param name="gridItem">列表中的一行数据</param>
        /// <param name="tabItem">EFTab控件对象</param>
        private void LoadTab(object gridItem, object tabItem)
        {
            var fdKeyId = gridItem.GetType().GetProperty("fdKeyId").GetValue(gridItem, null);
            Dictionary<string, string> args = new Dictionary<string, string>();
            args.Add("fdEquipmentId", fdKeyId.ToString());
            args.Add("fdStandardsForm", "1");
            if (tabItem != null)
            {
                (tabItem as EFTabItem).Content = null;
                (tabItem as EFTabItem).LoadView(TabToPageName[tabItem], args);
            }
        }

        # region 新增 修改 删除 生效 复制按钮

        /// <summary>
        /// 点击新增按钮，弹出新增页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnInsertButtonClick(object sender, RoutedEventArgs e)
        {
            ButtonName = "insert";
            EIInfo eiInfo = new EIInfo();
            base.OnInsertButtonClickPopup(eiInfo, "设备卡片-新增", "insert", null, sender, e);
        }

        /// <summary>
        /// 点击修改按钮，弹出新增页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnUpdateButtonClick(object sender, RoutedEventArgs e)
        {
            ButtonName = "update";
            IList<EIRow> _list = this.grid.GetCheckedEIRows() == null ? new List<EIRow>() : this.grid.GetCheckedEIRows();

            EIInfo eiInfo = new EIInfo();
            EIBlock eIBlock = new EIBlock("result");
            EIRow row = new EIRow();
            if (_list.Count > 0)
            {
                row = BaseTools.GetEIRowByOldEIRow(this.EIDataContext.GetBlock("result").GetColumns(), _list[0]);
            }
            eIBlock.SetRow(0, row);
            eiInfo.AddBlock(eIBlock);

            base.OnUpdateButtonClickPopup(eiInfo, "设备卡片-修改", "update", null, sender, e);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnDeleteButtonClick(object sender, RoutedEventArgs e)
        {
            ButtonName = "delete";
            base.OnDeleteButtonClick(sender, e);
        }

        /// <summary>
        /// 生效
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnEffectButtonClick(object sender, RoutedEventArgs e)
        {
            ButtonName = "effect";
            base.OnModifyButtonClick("effect", "生效", sender, e);
        }        

        /// <summary>
        /// 复制按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnCopyButtonClick(object sender, RoutedEventArgs e)
        {
            ButtonName = "copy";
            TempButton = sender as Button;
            TempButton.IsEnabled = false;

            List<EIRow> EFGridCheckedRows = this.grid.CheckedEIRows;
            if (EFGridCheckedRows.Count != 1)
            {
                BaseTools.OpenEFWindowAlert("请选择一条记录进行复制！", WindowAlertClosed);
                return;
            }
            else
            {
                EIInfo eiInfo = new EIInfo();
                EIRow row = BaseTools.GetEIRowByOldEIRow(this.EIDataContext.GetBlock("result").GetColumns(), EFGridCheckedRows[0]);
                eiInfo.AddBlock("result").SetRow(0, row);
                eiInfo.AddBlock(this.EIDataContext.GetBlock("cmes.ce.status"));
                eiInfo.AddBlock(this.EIDataContext.GetBlock("cmes.ce.intactType"));
                eiInfo.AddBlock(this.EIDataContext.GetBlock("cmes.cp.engineering"));
                eiInfo.AddBlock(this.EIDataContext.GetBlock("cmes.ce.department"));
                eiInfo.AddBlock(this.EIDataContext.GetBlock("cmes.ce.equipmentSource"));
                eiInfo.AddBlock(this.EIDataContext.GetBlock("cmes.ce.equipmentClass"));
                EquipmentCardCopy view = new EquipmentCardCopy();//构造一个新的修改页面
                view.EIDataContext = new Platform.Core.UI.EIDataContext();
                view.EIDataContext.Update(eiInfo);

                view.fdStatus.Value = "草拟";
                if (("在库".Equals(this.grid.CheckedEIRows[0]["fdUsingType"]) || "报废".Equals(this.grid.CheckedEIRows[0]["fdUsingType"])))
                {
                    view.fdDepartmentId.Label = "使用部门";
                    view.fdDepartmentId.eRegex = "";
                    view.fdDepartmentId.eValidateErrorPrompt = "";
                }

                view.classCustom.eViewInitParams = "bindingService=ZM10.query,columns=fdCode|fdName,queryConditions=fdCode|fdName,initParam=fdToencode:" + this.fdToencode.Value + "|fdIsLeaf:1";
                CmesWindows _popup = new CmesWindows();//构造一个弹出页面
                _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
                _popup.Header = "设备卡片复制";//设置Title
                _popup.Content = view;//让新增页面在弹出窗口显示
                _popup.Closed += new EventHandler<WindowClosedEventArgs>(InsertWindow_Closed);
                _popup.ShowDialog();//模态显示弹出窗口
            }
        }
        #endregion

        #region 引入标准
        /// <summary>
        /// 引入标准
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnAddstandardButtonClick(object sender, RoutedEventArgs e)
        {
            TempButton = sender as Button;
            TempButton.IsEnabled = false;
            int count = this.grid.CheckedEIRows.Count;
            if (count != 1)
            {
                this.OpenEFWindowAlert("请选择一条记录进行存为标准的操作！", true);
                return;
            }

            ButtonName = "addStandard";
            base.OnModifyButtonClick("addStandard", "引入标准", sender, e);
        }

        /// <summary>
        /// 重写基类的DoModifyOperationCompleted方法（为按钮“引入标准”而重写）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void DoModifyOperationCompleted(object sender, Platform.Core.ServiceModel.DoWorkCompletedEventArgs e)
        {
            EIInfo inInfo = e.EIInfo;
            if (inInfo.Status == -1)
            {
                //引入标准：判断是否找到对应的标准设备
                if (ButtonName.Equals("addStandard"))
                {
                    BaseTools.OpenEFWindowConfirm("没有找到对应的标准设备，是否引入其它标准设备的标准信息？", AddOtherStandard);
                    return;
                }

                this.OpenEFWindowAlert(inInfo.GetMsg(), true);//修改状态按钮执行失败后，按钮生效
                return;
            }
            else
            {
                base.UpdateData(e.EIInfo);
                this.TempButtonOpen(true);//修改状态按钮执行成功后，按钮生效

                //引入标准后刷新各标准页签
                if (ButtonName.Equals("addStandard"))
                {                    
                    if (IsStandardPage(this.tabPage.SelectedItem))
                    {
                        LoadTab(this.grid.SelectedItem, this.tabPage.SelectedItem);
                    }
                }
                if (ButtonName.Equals("addStandard") || ButtonName.Equals("saveStandard"))
                {
                    this.OpenEFWindowAlert("操作成功", false);
                }
            }
        }

        /// <summary>
        /// 引入其它标准设备的所有标准
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddOtherStandard(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == null || !e.DialogResult.Value)
            {
                this.TempButtonOpen(true);
                return;
            }

            if (e.DialogResult.Value)
            {
                Dictionary<string, object> args = new Dictionary<string, object>();
                args.Add("fdToencode", this.fdToencode.Value.ToString());
                args.Add("cordKeyId", this.grid.CheckedEIRows[0]["fdKeyId"]);
                EIInfo eiInfo = new EIInfo();
                eiInfo.SetAttributes(args);
                eiInfo.Attributes.Add(EIConstants.ServiceNameKey, "ZMCEB1");
                eiInfo.Attributes.Add(EIConstants.MethodNameKey, "initLoad");

                this.Submit(eiInfo, OnQueryOtherStandardWorkCompleted);
            }
        }

        /// <summary>
        /// 查询其它的标准设备后的回调函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnQueryOtherStandardWorkCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status != -1)
            {
                AddOtherStandard view = new AddOtherStandard();//构造一个新的修改页面
                view.EIDataContext = new Platform.Core.UI.EIDataContext();
                view.EIDataContext.Update(e.EIInfo);

                CmesWindows _popup = new CmesWindows();//构造一个弹出页面
                _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
                _popup.Header = "引入其他标准设备的标准信息";//设置Title
                _popup.Content = view;//让新增页面在弹出窗口显示
                _popup.Closed += new EventHandler<WindowClosedEventArgs>(InsertWindow_Closed);
                _popup.ShowDialog();//模态显示弹出窗口
            }
            else
            {
                BaseTools.OpenEFWindowAlert("该设备分类下没有其它的标准设备！", null);
                this.TempButtonOpen(true);
            }
        }

        /// <summary>
        /// 判断当前的页签是否是各标准页签
        /// </summary>
        /// <param name="tab"></param>
        /// <returns></returns>
        public bool IsStandardPage(object tab)
        {
            if (tab.Equals(this.tab5))
                return true;
            if (tab.Equals(this.tab6))
                return true;
            if (tab.Equals(this.tab7))
                return true;
            if (tab.Equals(this.tab8))
                return true;
            return false;
        }
        #endregion

        #region 存为标准
        /// <summary>
        /// 存为标准
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnSavestandardButtonClick(object sender, RoutedEventArgs e)
        {
            TempButton = sender as Button;
            TempButton.IsEnabled = false;
            int count = this.grid.CheckedEIRows.Count;
            if (count != 1)
            {
                this.OpenEFWindowAlert("请选择一条记录进行存为标准的操作！", true);
                return;
            }

            ButtonName = "saveStandard";
            base.OnModifyButtonClick("saveStandard", "存为标准", sender, e);
        }
        #endregion

        /// <summary>
        /// 只有草拟的可以删除，生效；
        /// 草拟不能引入标准，存为标准；
        /// </summary>
        /// <param name="_eIRows"></param>
        /// <returns></returns>
        public override bool BeforeMethod(List<EIRow> _eIRows)
        {
            if (ButtonName.Equals("delete") || ButtonName.Equals("update"))
            {
                foreach (EIRow row in _eIRows)
                {
                    if (row["fdStatus"].Equals("生效"))
                    {
                        BaseTools.OpenEFWindowAlert("只有状态为草拟的设备才可以" + TempButton.Content + "，请重新选择!", null);
                        this.TempButtonOpen(true);                        
                        return false;
                    }
                }                
            }
            else if(ButtonName.Equals("effect"))
            {
                foreach (EIRow row in _eIRows)
                {
                    if (row["fdStatus"].Equals("生效"))
                    {
                        BaseTools.OpenEFWindowAlert("只有状态为草拟的设备才可以" + TempButton.Content + "，请重新选择!", null);
                        this.TempButtonOpen(true);                        
                        return false;
                    }
                    if (row["fdIsFlinging"].Equals("是"))
                    {
                        BaseTools.OpenEFWindowAlert("临时设备不能" + TempButton.Content + "！", null);
                        this.TempButtonOpen(true);
                        return false;
                    }
                }  
            }
            else if (ButtonName.Equals("addStandard") || ButtonName.Equals("saveStandard"))
            {
                foreach (EIRow row in _eIRows)
                {
                    if (row["fdStatus"].Equals("草拟"))
                    {
                        BaseTools.OpenEFWindowAlert("状态为草拟的设备不能" + TempButton.Content + "！请重新选择!", null);
                        this.TempButtonOpen(true);
                        return false;
                    }
                } 
            }
            return true;
        }
        


        /// <summary>
        /// 弹出窗口关闭时执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InsertWindow_Closed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == true)
            {
                //刷新Grid区域
                this.grid.Refresh();

                //引入标准后要刷新标准页签
                if (ButtonName.Equals("addStandard"))
                {
                    if (IsStandardPage(this.tabPage.SelectedItem))
                    {
                        LoadTab(this.grid.SelectedItem, this.tabPage.SelectedItem);
                    }
                }
            }

            //按钮生效
            base.TempButtonOpen(true);
            //超链接生效
            if (base.TempHyperlink != null)
            {
                base.TempHyperlink.IsEnabled = true;
                base.TempHyperlink = null;
            }
        }

        /// <summary>
        /// 新增或修改之前的数据传输
        /// 构造新增页面内容、弹出页面
        /// </summary>
        /// <param name="eIInfo"></param>
        /// <param name="title"></param>
        public override void OpenPopup(EIInfo _eIInfo, string _title, string _dialogType, string _args)
        {
            _eIInfo.AddBlock(this.EIDataContext.GetBlock("cmes.ce.status"));
            _eIInfo.AddBlock(this.EIDataContext.GetBlock("cmes.ce.intactType"));
            _eIInfo.AddBlock(this.EIDataContext.GetBlock("cmes.cp.engineering"));
            _eIInfo.AddBlock(this.EIDataContext.GetBlock("cmes.ce.department"));
            _eIInfo.AddBlock(this.EIDataContext.GetBlock("cmes.ce.equipmentSource"));
            _eIInfo.AddBlock(this.EIDataContext.GetBlock("cmes.ce.equipmentClass"));
            _eIInfo.AddBlock(new EquipmentCardBlock().getIsFiling("cmes.ce.isFiling"));
            EquipmentCard view = new EquipmentCard(_dialogType);//构造一个新的修改页面
            view.EIDataContext = new Platform.Core.UI.EIDataContext();
            view.EIDataContext.Update(_eIInfo);

            if ("insert".Equals(_dialogType))
            {
                view.fdIntactType.Value = "完好";
                view.fdUsingType.Value = "封存";
                view.fdIsFlinging.Value = "否";
                view.fdStatus.Value = "草拟";
            }
            else if("update".Equals(_dialogType))
            {
                if ("是".Equals(this.grid.CheckedEIRows[0]["fdIsFlinging"]))
                {
                    view.fdCode.eLabel = "设备编号";
                    view.fdCode.eRegex = "^[a-zA-Z0-9]{0,20}$";
                    view.fdCode.eValidateErrorPrompt = "输入0~20个数字、字母";
                    view.fdCode.Value = "";
                }
                if (("在库".Equals(this.grid.CheckedEIRows[0]["fdUsingType"]) || "报废".Equals(this.grid.CheckedEIRows[0]["fdUsingType"])))
                {
                    view.fdDepartmentId.Label = "使用部门";
                    view.fdDepartmentId.eRegex = "";
                    view.fdDepartmentId.eValidateErrorPrompt = "";
                }
            }


            view.classCustom.eViewInitParams = "bindingService=ZM10.query,columns=fdCode|fdName,queryConditions=fdCode|fdName,initParam=fdToencode:" + this.fdToencode.Value + "|fdIsLeaf:1";
            CmesWindows _popup = new CmesWindows();//构造一个弹出页面
            _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
            _popup.Header = _title == null ? "" : _title;//设置Title
            _popup.Content = view;//让新增页面在弹出窗口显示
            _popup.Closed += new EventHandler<WindowClosedEventArgs>(InsertWindow_Closed);
            _popup.ShowDialog();//模态显示弹出窗口
        }

        #region 查看明细
        /// <summary>
        /// 明细
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton link = sender as HyperlinkButton;

            EIRow row = (link.ParentOfType<GridViewRow>().Item as UIBaseEntity).GetEIRow();
            EIInfo eiInfo = new EIInfo();
            EIBlock eIBlock = new EIBlock("result");
            eIBlock.SetRow(0, row == null ? new EIRow() : row);
            eiInfo.AddBlock(eIBlock);

            base.OnHyperlinkButtonClickPopup(eiInfo, "设备卡片-查看", "detail", null, sender, e);
        }
        #endregion
    }
}

